package kz.pompei.ifacer.main;

import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;

public class KeyManager {
  private static class Trap {
    private final AbstractAction1 action;
    private final KeyAcceptor acceptor;
    
    public Trap(AbstractAction1 action, KeyAcceptor acceptor) {
      this.action = action;
      this.acceptor = acceptor;
    }
    
    public static Trap parse(String key, AbstractAction1 action) {
      return new Trap(action, KeyAcceptor.parse(key));
    }
    
    public boolean accept(KeyEvent e) {
      return acceptor.accept(e);
    }
    
    @Override
    public String toString() {
      return "" + acceptor;
    }
  }
  
  private final List<Trap> traps = new ArrayList<>();
  
  public void add(AbstractAction1 action, String... keys) {
    for (String key : keys) {
      traps.add(Trap.parse(key, action));
    }
  }
  
  public boolean dispatch(KeyEvent e) {
    for (Trap trap : traps) {
      if (trap.accept(e)) {
        trap.action.execute();
        return true;
      }
    }
    return false;
  }
}
